package com.ruoyi.water.controller;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.DateUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.water.domain.Leakage;
import com.ruoyi.water.service.ILeakageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 漏耗管理Controller
 *
 * @author ruoyi
 * @date 2025-09-29
 */
@RestController
@RequestMapping("/water/leakage")
public class LeakageController extends BaseController
{
    @Autowired
    private ILeakageService leakageService;

    /**
     * 查询漏耗管理列表
     */
    @PreAuthorize("@ss.hasPermi('water:leakage:list')")
    @GetMapping("/list")
    public AjaxResult list(Leakage leakage,
                           @RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize) {
        // 1. 构建分页对象
        Page<Leakage> page = new Page<>(pageNum, pageSize);

        // 2. 构建查询条件（非空字段才作为查询条件）
        QueryWrapper<Leakage> queryWrapper = new QueryWrapper<>();
        // 如果ID不为空，则添加精确查询条件
        if (leakage.getId() != null) {
            queryWrapper.eq("id", leakage.getId());
        }
        // 如果泄漏类型不为空，则添加精确查询条件
        if (leakage.getLeakageType() != null) {
            queryWrapper.eq("leakageType", leakage.getLeakageType());
        }
        // 如果分析日期不为空，则添加精确查询条件
        if (leakage.getAnalyseDate() != null) {
            queryWrapper.eq("analyseDate", leakage.getAnalyseDate());
        }
        // 如果状态不为空，则添加精确查询条件
        if (leakage.getStatus() != null) {
            queryWrapper.eq("status", leakage.getStatus());
        }

        // 3. 调用MyBatis-Plus的分页查询方法
        IPage<Leakage> pageResult = leakageService.page(page, queryWrapper);

        // 4. 封装分页结果（兼容若依的TableDataInfo格式）
        return AjaxResult.success()
                .put("total", pageResult.getTotal())        // 总条数
                .put("rows", pageResult.getRecords())      // 当前页数据
                .put("pageNum", pageResult.getCurrent())   // 当前页码
                .put("pageSize", pageResult.getSize())     // 每页条数
                .put("pages", pageResult.getPages());      // 总页数
    }

    /**
     * 导出漏耗管理列表
     */
    @PreAuthorize("@ss.hasPermi('water:leakage:export')")
    @Log(title = "漏耗管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Leakage leakage)
    {
        QueryWrapper<Leakage> queryWrapper = new QueryWrapper<>(leakage);
        List<Leakage> list = leakageService.list(queryWrapper);
        ExcelUtil<Leakage> util = new ExcelUtil<Leakage>(Leakage.class);
        util.exportExcel(response, list, "漏耗管理数据");
    }

    /**
     * 获取漏耗管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('water:leakage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        // 使用MyBatis-Plus的getById方法
        return success(leakageService.getById(id));
    }

    /**
     * 新增漏耗管理
     */
    @PreAuthorize("@ss.hasPermi('water:leakage:add')")
    @Log(title = "漏耗管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Leakage leakage)
    {
        // 设置记录时间为当前时间
        leakage.setRecordDate(new Date());
        // 使用MyBatis-Plus的save方法
        return toAjax(leakageService.save(leakage) ? 1 : 0);
    }

    /**
     * 修改漏耗管理
     */
    @PreAuthorize("@ss.hasPermi('water:leakage:edit')")
    @Log(title = "漏耗管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Leakage leakage)
    {
        // 使用MyBatis-Plus的updateById方法
        return toAjax(leakageService.updateById(leakage) ? 1 : 0);
    }

    /**
     * 删除漏耗管理
     */
    @PreAuthorize("@ss.hasPermi('water:leakage:remove')")
    @Log(title = "漏耗管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 使用MyBatis-Plus的removeByIds方法
        return toAjax(leakageService.removeByIds(List.of(ids)) ? ids.length : 0);
    }

    /**
     * 计算指定日期范围内的漏耗数据
     */
    @PreAuthorize("@ss.hasPermi('water:leakage:calculate')")
    @Log(title = "漏耗管理", businessType = BusinessType.OTHER)
    @PostMapping("/calculateByDateRange")
    public AjaxResult calculateByDateRange(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        int count = leakageService.calculateLeakageByDateRange(startDate, endDate);
        return AjaxResult.success("成功计算 " + count + " 条漏耗数据");
    }
}
